<template>
  <div class="login">
    <div class="logo-box">
      <i class="login-logo"></i>
    </div>
    <el-form ref="loginForm"
             :model="loginForm"
             :rules="loginRules"
             class="login-form"
             label-position="top">
      <h3 class="title">登录</h3>
      <el-form-item prop="username"
                    label="用户名"
                    class="login-form-item">
        <el-input v-model="loginForm.username"
                  type="text"
                  auto-complete="off"
                  placeholder="请输入用户名">
        </el-input>
        <i class="icon icon-username"></i>
      </el-form-item>
      <el-form-item prop="password"
                    label="密码"
                    class="login-form-item">
        <el-input v-model="loginForm.password"
                  type="password"
                  auto-complete="off"
                  placeholder="请输入密码">
        </el-input>
        <i class="icon icon-password"></i>
      </el-form-item>
      <el-form-item prop="imageCode"
                    label="验证码"
                    class="login-form-item">
        <el-col :span="16">
          <el-input v-model="loginForm.imageCode"
                    auto-complete="off"
                    placeholder="请输入验证码"
                    @keyup.enter.native="handleLogin">
          </el-input>
        </el-col>
        <el-col :span="8"
                class="code-box">
          <img :src="codeUrl"
               class="img-code"
               title="点击重新获取"
               @click="getCode" />
        </el-col>
      </el-form-item>
      <!-- <el-checkbox v-model="loginForm.rememberMe"
                   style="margin:0px 0px 25px 0px;">记住密码</el-checkbox> -->
      <el-form-item style="width:100%;">
        <el-button :loading="loading"
                   size="medium"
                   type="primary"
                   style="width:100%;"
                   class="login-btn"
                   @click.native.prevent="handleLogin">
          <span v-if="!loading">登录</span>
          <span v-else>登录中...</span>
        </el-button>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <div class="el-login-footer">
      <!-- <span>Copyright © 2018-2020 ruoyi.vip All Rights Reserved.</span> -->
    </div>
  </div>
</template>

<script>
import { getCodeImg, getKeys } from "@/api/login";
import { saveLoginSource } from "@/utils/handleLoginSource"
import Cookies from "js-cookie";
import { encrypt, decrypt } from '@/utils/jsencrypt'
import { mapGetters, mapState } from 'vuex'
const defaultSettings = require('@/settings.js')
const sm2 = require('sm-crypto').sm2
const cipherMode = 1

export default {
  name: "Login",
  computed: {
    ...mapState(["notice"]),
    ...mapGetters(["noticeList", "userCode"])
  },
  data() {
    return {
      codeUrl: "",
      cookiePassword: "",
      loginForm: {
        username: "", // 510212196310233000
        // username: "xiaorenjie", // 510212196310233000
        password: "",
        // password: "Szy@2021.",
        rememberMe: false,
        imageCode: "",
        imageKey: ""
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "用户名不能为空" }
        ],
        password: [
          { required: true, trigger: "blur", message: "密码不能为空" }
        ],
        imageCode: [
          { required: true, trigger: "blur", message: "验证码不能为空" }
        ],
      },
      loading: false,
      redirect: undefined,
      // 公钥
      pubkeys: undefined,
      websocket: null,
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  created() {
    // this.getCookie();
    this.getKeys();
    this.getCode();
  },
  methods: {
    initWebSocket() {
      //判断当前浏览器是否支持WebSocket, 主要此处要更换为自己的地址
      let userCode = this.userCode;
      let url = 'ws://' + defaultSettings.targetUrl.split('http://')[1] + '/SzyWebsocket/' + userCode;

      if ('WebSocket' in window) {
        this.websocket = new WebSocket(url);
      } else {
        alert('Not support websocket')
      }
      //连接成功建立的回调方法
      this.websocket.onopen = (event) => {

      }
      //接收到消息的回调方法
      this.websocket.onmessage = (event) => {
        var list = []
        list = list.concat(JSON.parse(event.data))
        this.$store.commit("SET_NOTICELIST", list);
      }
    },
    /** 获取公钥 */
    getKeys() {
      getKeys().then((res) => {
        if (res.status == 200) {
          this.pubkeys = res.data;
        }
      });
    },
    getCode() {
      getCodeImg().then(res => {
        // console.log(res)
        let { data } = res
        this.codeUrl = "data:image/gif;base64," + data.imageBase64;
        this.loginForm.imageKey = data.key;
      });
    },
    getCookie() {
      const username = Cookies.get("zy-username");
      const password = Cookies.get("zy-password");
      const rememberMe = Cookies.get('zy-rememberMe');
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      };
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("zy-username", this.loginForm.username, { expires: 30 });
            Cookies.set("zy-password", encrypt(this.loginForm.password), { expires: 30 });
            Cookies.set('zy-rememberMe', this.loginForm.rememberMe, { expires: 30 });
          } else {
            Cookies.remove("zy-username");
            Cookies.remove("zy-password");
            Cookies.remove('zy-rememberMe');
          }
          let password = "04" + sm2.doEncrypt(this.loginForm.password, this.pubkeys, cipherMode);
          let userInfo = { ...this.loginForm };
          userInfo.password = password;
          this.$store.dispatch("Login", userInfo).then((res) => {
            if (res.status == '101') {
              this.loading = false;
              let errMsg = res.errors[0].message
              this.$message({
                message: errMsg,
                type: 'error',
                offset: 60
              });
              if (errMsg !== '验证码不正确！') {
                this.getCode();
              }
            } else if (res.status == '200') {
              this.initWebSocket()
              this.$router.push({ path: "/" });
              // 保存登录来源
              saveLoginSource('loginLocal');
            }
          })
            .catch(() => {
              this.loading = false;
              this.getCode();
            });
        }
      });
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/image/login/login-background.png");
  background-size: cover;
}
.title {
  font-size: 24px;
  margin: 0px auto 30px auto;
  text-align: center;
  color: #4e7fff;
}
.logo-box {
  display: flex;
  justify-content: center;
  width: 398px;
  height: 500px;
  background: rgba(0, 0, 0, 0.3);
  .login-logo {
    display: inline-block;
    width: 313px;
    height: 81px;
    background: url("../assets/image/login/login_logo.png") no-repeat;
    margin-top: 68px;
  }
}
.login-form {
  border-radius: 0 6px 6px 0;
  background: #ffffff;
  width: 452px;
  height: 500px;
  padding: 68px 50px 5px 50px;
  box-sizing: border-box;
  .login-form-item {
    position: relative;
    .icon {
      position: absolute;
      top: 8px;
      right: 10px;
      width: 24px;
      height: 24px;
      z-index: 6;
      &.icon-username {
        background: url("../assets/image/login/icon_username.png") no-repeat;
      }
      &.icon-password {
        background: url("../assets/image/login/icon_password.png") no-repeat;
      }
    }
  }
  /deep/.el-input__inner {
    height: 40px;
    line-height: 40px;
    font-size: 16px;
    color: #0a1629;
    padding: 0 36px 0 15px;
  }
  .login-btn {
    height: 54px;
    background: linear-gradient(135deg, #4e85ff 0%, #4b60ff 100%);
    font-size: 20px;
    font-weight: bold;
    letter-spacing: 2px;
  }
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

/deep/.el-form--label-top .el-form-item__label {
  padding: 0;
}
/deep/.el-form-item--medium .el-form-item__label {
  line-height: 28px;
  color: #3a3f63;
}
/deep/.el-form-item__label:before {
  display: none;
}
.code-box {
  text-align: right;
  height: 38px;
}
.img-code {
  width: 110px;
  height: 38px;
  cursor: pointer;
}
</style>
